<?php
declare(strict_types=1);
/**
 * @project: 兔兔找图微信小程序
 * @author: kert
 * @date: 2023/5/16
 * @link: https://www.tutudati.com/
 * @site: 微信搜索-兔兔找图
 */
namespace App\Logic\User\Repository\Image;

use App\Logic\User\Repository\UserRepositoryInterface;
use App\Models\User\Image\ImageModel;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ImageRepository implements UserRepositoryInterface
{

    public function repositorySelect(Closure $closure, int $perSize, array $searchFields = []): array
    {
        $build = ImageModel::query()
            ->with(["author:uid,qr_url,nickname"])
            ->with(["user:uid,nickname,avatar_url"])
            ->with(["category:uid,title"])
            ->with(["series:uid,title,bg_color"])
            ->where($closure);
        $type = request()->get("type", -1);
        if ($type == 2) {// 热门
            $build->orderByDesc("download");
        }
        if ($type == 1 || $type == -1) {// 最新
            $build->orderByDesc("id");
        }
        if ($type == 0) {// 推荐
            $build->where("is_recommend", "=", 1)->orderByDesc("sort");
        }
        $build->orderByDesc("id");
        $items = $build->paginate($perSize, $searchFields);

        return [
            "items" => $items->items(),
            "total" => $items->total(),
            "page" => $items->currentPage(),
            "size" => $items->perPage(),
        ];
    }

    public function repositoryCreate(array $insertInfo): bool
    {
        Db::beginTransaction();
        try {
            $imageModel = ImageModel::query()->create($insertInfo["image"]);
            $imageItemModel = DB::table("image_item")->insert($insertInfo["image_item"]);
            if (!empty($imageModel->getKey()) && $imageItemModel) {
                DB::commit();
                return true;
            }
            DB::rollBack();
            return false;
        } catch (\Throwable $throwable) {
            Log::error($throwable->getMessage());
            DB::rollBack();
            return false;
        }
    }

    public function repositoryFind(Closure $closure, array $searchFields = []): array
    {
        $bean = ImageModel::query()
            ->with(["category:uid,title"])
            ->with(["series:uid,title"])
            ->where($closure)
            ->first($searchFields);
        return !empty($bean) ? $bean->toArray() : [];
    }

    public function repositoryUpdate(array $updateWhere, array $updateInfo): int
    {
        return 0;
    }

    public function repositoryWhereInDelete(array $deleteWhere, string $field): int
    {
        return 0;
    }

    public function repositoryDelete(array $deleteWhere): int
    {
        return 0;
    }
}
